﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ud_ImageSlideShow.Data
{
    public class DBImageSlideShowCategory
    {
        readonly ImageSlideShowDc db = new ImageSlideShowDc();

        public ImageSlideShowCategory GetOne(int id)
        {
            var result = from p in db.ImageSlideShowCategories
                         where p.ID.Equals(id)
                         select p;
            return result.FirstOrDefault();
        }

        public List<ImageSlideShowCategory> GetAll(int moduleID)
        {
            var result = from p in db.ImageSlideShowCategories
                         where p.ModuleID.Equals(moduleID)
                         orderby p.LastModified descending
                         select p;
            return result.ToList();
        }

        public bool Delete(int id)
        {
            bool flag = false;
            ImageSlideShowCategory item = GetOne(id);
            db.ImageSlideShowCategories.DeleteOnSubmit(item);
            try
            {
                db.SubmitChanges();
                flag = true;
            }
            catch
            { }
            return flag;
        }

        public bool Create(int moduleID, string name, int parentId)
        {
            bool flag = false;

            ImageSlideShowCategory item = new ImageSlideShowCategory
                                      {
                                          ModuleID = moduleID,
                                          Name = name,
                                          ParentID = parentId,
                                          LastModified = DateTime.UtcNow
                                      };
            db.ImageSlideShowCategories.InsertOnSubmit(item);
            try
            {
                db.SubmitChanges();
                flag = true;
            }
            catch { }
            return flag;
        }

        public bool Update(int id, string name, int parentId)
        {
            bool flag = false;

            ImageSlideShowCategory item = GetOne(id);
            if (item != null)
            {
                item.Name = name;
                item.ParentID = parentId;
                item.LastModified = DateTime.UtcNow;
                try
                {
                    db.SubmitChanges();
                    flag = true;
                }
                catch { }
            }
            return flag;
        }

        public void DeleteByModule(int moduleID)
        {
            var result = from p in db.ImageSlideShowCategories
                         where p.ModuleID.Equals(moduleID)
                         select p;
            db.ImageSlideShowCategories.DeleteAllOnSubmit(result);
            db.SubmitChanges();
        }
    }
}
